package com.tungse.juc.product_consumers;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PCDemo1 {

    public static void main(String[] args) {
        Data1 data = new Data1();
        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();//生产者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();//消费者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();//生产者

        new Thread(() -> {
            for (int i=0; i<10; i++){
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();//消费者
    }

}


//执行顺序   等待  业务  通知
class Data1 {//资源类
    private int num = 0;

    Lock lock = new ReentrantLock();
    //Condition 能够做到精准的通知
    Condition condition = lock.newCondition();

    //+1
    public void increment() throws InterruptedException {
        lock.lock();
        try{
            while (num != 0) {
                //等待
                condition.await();
            }
            num++;//业务
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            //通知其他线程， 生产完毕了
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    //-1
    public void decrement() throws InterruptedException {
        lock.lock();
        try{
            while (num == 0) {
                //等待
                condition.await();
            }
            num--;//业务
            System.out.println(Thread.currentThread().getName() + "=>" + num);
            //通知其他线程， 消费完毕了
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }
}